<template>
  <div class="inventory-adjust">
    <div class="card inventory-adjust__header">
      <el-form inline>
        <el-form-item label="物品类型">
          <el-cascader
            v-model="params.goodsTypeId"
            :options="goodsTypeOptions"
            :props="{ value: 'id', label: 'name' }"
            clearable
          />
        </el-form-item>
        <el-form-item label="申请人">
          <el-input v-model="params.name" placeholder="申请人姓名" clearable />
        </el-form-item>

        <el-form-item label="审核状态">
          <el-select
            v-model="params.state"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in examineStateFormat"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="申请时间">
          <el-date-picker
            v-model="params.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            size="medium"
            type="danger"
            @click="handleReset"
          >重置</el-button>

          <el-button
            size="medium"
            type="primary"
            @click="handleSearch"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="card inventory-adjust__content">
      <el-table
        v-loading="loading"
        :data="list"
        border
        stripe
      >
        <el-table-column
          label="物品类型"
          align="center"
          prop="goodsType.name"
        />

        <el-table-column
          label="调整数量"
          align="center"
          prop="adjust_quantity"
        />

        <el-table-column
          label="调整前库存数"
          align="center"
          prop="old_quantity"
        />

        <el-table-column
          label="调整后库存数"
          align="center"
          prop="new_quantity"
        />

        <el-table-column
          label="调整原因"
          align="center"
          prop="reason"
        />

        <el-table-column
          label="申请人"
          align="center"
          prop="user.username"
        />

        <el-table-column
          label="申请时间"
          align="center"
          prop="adjust_time"
        />

        <el-table-column
          label="审核状态"
          align="center"
          prop="status"
        >
          <template v-slot="{ row }">
            <el-tag
              :type="examineState[row.status].tagType"
            >
              {{ examineState[row.status].label }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          align="center"
        >
          <template v-slot="{ row }">
            <el-dropdown trigger="click" @command="handleDropdownItemClick($event, row.id)">
              <el-button
                :disabled="row.status !== 0"
                size="mini"
                type="text"
              >
                审核
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="success">通过</el-dropdown-item>
                <el-dropdown-item command="fail">拒绝</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

            <el-button
              :disabled="row.status !== 0"
              type="text"
              size="mini"
              style="margin-left: 10px;"
              @click="handleEditInventoryAdjust(row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="inventory-adjust__content__pagination">
        <Pagination
          style="margin-top: 0; padding: 0;"
          :total="total"
          :limit="params.paginate"
          @pagination="pagination"
        />
      </div>
    </div>
    <EditInventoryAdjustDialog
      :visible.sync="editDialogVisible"
      :loading="editDialogConfirmLoading"
      :record="currentInventoryAdjustRecord"
      @confirm="handleEditConfirm"
    />
  </div>
</template>

<script>
import {
  getInventoryAdjustRecords,
  examineInventoryAdjust,
  getGoodsType,
  editInventoryAdjustRecord
} from '@/api/officeSuppliesManagement'
import Pagination from '@/components/Pagination/index.vue'
import EditInventoryAdjustDialog
from '@/views/officeSuppliesManagement/components/inventoryAdjustRecord/EditInventoryAdjustDialog.vue'
import { sleep } from '@/utils'
export default {
  name: '',
  components: {
    Pagination,
    EditInventoryAdjustDialog
  },
  data() {
    return {
      list: [],
      params: {
        goodsTypeId: null,
        time: [],
        name: '',
        state: null,
        page: 1,
        paginate: 10
      },
      loading: false,
      total: 0,
      goodsTypeOptions: [],

      examineState: {
        0: {
          label: '待审核',
          tagType: 'info',
          value: 'wait'
        },

        1: {
          label: '审核成功',
          tagType: 'success',
          value: 'success'
        },

        2: {
          label: '审核失败',
          tagType: 'danger',
          value: 'failed'
        }
      },

      pickerOptions: {
        disabledDate(time) {
          const now = Date.now()
          return time.getTime() > now
        }
      },

      examineInfo: {
        id: null,
        state: '',
        failed_reason: null
      },

      editDialogVisible: false,
      editDialogConfirmLoading: false,
      currentInventoryAdjustRecord: null
    }
  },

  computed: {
    examineStateFormat() {
      return Object.values(this.examineState).map(item => {
        return {
          label: item.label,
          value: item.value
        }
      })
    }
  },

  created() {
    this.init()
  },

  methods: {
    init() {
      Promise.allSettled([
        this.getInventoryAdjustRecords(),
        this.getGoodsType()
      ])
    },

    async getInventoryAdjustRecords() {
      this.loading = true
      try {
        const res = await getInventoryAdjustRecords(this.generateParams())
        this.list = res.data
        this.total = res.meta.total
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '信息获取失败')
      } finally {
        await sleep()
        this.loading = false
      }
    },

    async getGoodsType() {
      try {
        const res = await getGoodsType()
        this.goodsTypeOptions = res.data
      } catch (error) {
        throw new Error(error?.response?.data?.message || '信息获取失败')
      }
    },

    generateParams() {
      const len = this.params.goodsTypeId?.length
      const goodsTypeId = len > 0 ? this.params.goodsTypeId[len - 1] : null
      return {
        ...this.params,
        time: this.params.time && this.params.time.length ? JSON.stringify(this.params.time) : null,
        goodsTypeId
      }
    },

    pagination(page) {
      this.params.page = page.page
      this.params.paginate = page.limit
      this.getInventoryAdjustRecords()
    },

    handleSearch() {
      this.params.page = 1
      this.getInventoryAdjustRecords()
    },

    handleReset() {
      this.params = this.$options.data().params
      this.getInventoryAdjustRecords()
    },

    handleDropdownItemClick(command, id) {
      this.examineInfo.id = id
      this.examineInfo.state = command
      const handle = {
        success: this.examineSuccessConfirm,
        fail: this.examineFailedConfirm
      }

      handle[command]()
    },

    examineSuccessConfirm() {
      this.$confirm(
        '是否确定审核通过？',
        '提示',
        {
          type: 'warning',
          showCancelButton: true
        }
      ).then(() => {
        this.examineInventoryAdjustFetch(this.examineInfo)
      })
    },

    examineFailedConfirm() {
      this.$prompt(
        '请输入拒绝原因',
        '拒绝原因',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: (val) => {
            return !!val
          },
          inputErrorMessage: '拒绝原因不能为空'
        }
      ).then(res => {
        this.examineInfo.failed_reason = res.value
        this.examineInventoryAdjustFetch(this.examineInfo)
      })
    },

    async examineInventoryAdjustFetch(params) {
      try {
        const res = await examineInventoryAdjust(params)
        this.$message.success('审核成功')
        this.refresh()
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '审核失败')
      }
    },

    refresh() {
      this.params = this.$options.data().params
      this.getInventoryAdjustRecords()
    },

    handleEditInventoryAdjust(row) {
      console.log('row --------->', row)
      this.currentInventoryAdjustRecord = row
      this.editDialogVisible = true
    },

    handleEditConfirm(e) {
      console.log('e --------->', e)
      this.editInventoryAdjustRecord(e)
    },

    async editInventoryAdjustRecord(params) {
      this.editDialogConfirmLoading = true
      try {
        const res = await editInventoryAdjustRecord(params)
        this.$message.success('修改成功')
        this.editDialogVisible = false
        this.refresh()
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '修改失败')
      } finally {
        this.editDialogConfirmLoading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.inventory-adjust {
  padding: 20px;

  &__header {
    padding: 20px 20px 0 20px !important;
    ::v-deep(.el-form-item) {
      margin-bottom: 20px;
      margin-right: 20px;
      //padding: 0 20px;
    }
  }

  &__content {

    &__header {
      margin-bottom: 20px;
    }

    &__pagination {
      margin-top: 20px;
      display: flex;
      justify-content: end;
    }
  }

  .card {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    margin-bottom: 20px;
  }

}
</style>
